<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    chartData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData(newValue, oldValue) {
      this.initChart()
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      const source = this.chartData.source
      const title = this.chartData.title
      var series = []
      for (var i = 0; i < source[0].length - 1; i++) {
        series.push(
          {
            type: 'bar',
            barMaxWidth: 40,
            label: {
              show: true,
              textStyle: {
                color: 'black'
              }
            }
          }
        )
      }
      var top = ''
      this.chart.setOption({
        title: {
          // show: showed, // 是否显示title
          text: title,
          top: top,
          left: 'center',
          textStyle: {
            color: 'black',
            fontSize: 20,
            fontWeight: 400
          }
        },
        legend: {
          top: '10%'
        },
        tooltip: {
        },
        grid: {
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [{
          type: 'category'
        }],
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          },
          minInterval: 1
        }],
        dataset: [{
          source: source
        }],
        series: series
      })
    }
  }
}
</script>
